package edu.ncut.vod.jsf.examonline.selfmadevalidator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlInputText;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import com.sun.faces.util.MessageFactory;

import edu.ncut.vod.jsf.examonline.managedbeans.AddStudentBean;

public class HumanIdValidator implements Validator {

    /**
     * validate field 'humanId':its length must be 15 or 18
     */
    public void validate(FacesContext context, UIComponent component,
            Object obj) throws ValidatorException {
        debug("method validate in class HumanIdValidator is called");

        String label = ((HtmlInputText) component).getLabel();

        if ("humanId".equals(label)) {
            String fieldValue = (String) obj; // get the value of field which needs validating

			FacesContext facesContext = FacesContext.getCurrentInstance();

            // validate field 'humanId':its length must be 15 or 18
            boolean lengthMatch = false;
            if(15 == fieldValue.length() || 18 == fieldValue.length()){
				lengthMatch = true;
			}

			// validate field 'humanId':it must be number or English letter
            Pattern charPattern = Pattern.compile("^[A-Za-z0-9]+$");
            Matcher charMatcher = charPattern.matcher(fieldValue);
            boolean charMatch= charMatcher.matches();

            if (!lengthMatch && charMatch) {//validate field 'fieldValue':its length must be 15 or 18
                FacesMessage msg = MessageFactory.getMessage(facesContext,"humanIdLength_mustBe15Or18","humanIdLength_mustBe15Or18");
                msg.setSeverity(FacesMessage.SEVERITY_WARN);
                facesContext.addMessage("addStudent:humanId", msg);
                setErrorMessageVisible();
                throw new ValidatorException(msg);
            }else if(lengthMatch && !charMatch){//validate field 'fieldValue':it must be number or English letter
                FacesMessage msg=MessageFactory.getMessage(facesContext,"humanIdLength_mustBeNumberOrEnglishLetter","humanIdLength_mustBeNumberOrEnglishLetter");
                msg.setSeverity(FacesMessage.SEVERITY_WARN);
                facesContext.addMessage("addStudent:humanId",msg);
                setErrorMessageVisible();
                throw new ValidatorException(msg);
            }else if(!lengthMatch && !charMatch){//validate field 'fieldValue':its length must be 15 or 18 and must be number or English letter
                FacesMessage msg=MessageFactory.getMessage(facesContext,"humanIdLength_isNot15Or18AndMustBeNumberOrEnglishLetter","humanIdLength_isNot15Or18AndMustBeNumberOrEnglishLetter");
                msg.setSeverity(FacesMessage.SEVERITY_WARN);
                facesContext.addMessage("addStudent:humanId",msg);
                setErrorMessageVisible();
                throw new ValidatorException(msg);
            }else{
				setErrorMessageInvisible();
			}
        }
    }

    /**
     * set error message tag of tag 'h:inputText' visible
     */
    public void setErrorMessageVisible(){
        debug("method setErrorMessageVisible in class HumanIdValidator is called");

        FacesContext context =FacesContext.getCurrentInstance();
        Application application=context.getApplication();
        AddStudentBean addStudentBean=(AddStudentBean)application.evaluateExpressionGet(context,"#{addStudentBean}",AddStudentBean.class);

        addStudentBean.setHumanIdNotice(true);
        addStudentBean.setHumanIdMessage(true);
    }

    /**
	 * set error message tag of tag 'h:inputText' invisible
	 */
    public void setErrorMessageInvisible(){
		debug("method setErrorMessageInvisible in class HumanIdValidator is called");

		FacesContext context =FacesContext.getCurrentInstance();
        Application application=context.getApplication();
        AddStudentBean addStudentBean=(AddStudentBean)application.evaluateExpressionGet(context,"#{addStudentBean}",AddStudentBean.class);

        addStudentBean.setHumanIdNotice(false);
        addStudentBean.setHumanIdMessage(false);
	}

    /**
     * print message on console
     * @param message
     */
    public void debug(String message) {
        System.out.println(message);
    }
}
